﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using WindowsInstaller;
using System.Data.OleDb;



namespace TMS
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (CheckApplicationUpdate()) return;    // update is needed, quit      
           // try
          //  {
                Application.Run(new LogonScreen());
         //   }
         //   catch (Exception e)
         //   {
         //       Mail error = new Mail();
         //       error.SendSupprtMail(e.ToString());
         //   }
        }

        //private variable that holds the main form
        private static MainForm form1;
        private static Users activeUser;

        //public property that provides a getter for main form
        public static MainForm GetMainForm
        {
            get { return form1; }
        }

        //public property that provides a setter for main form
        public static void SetMainForm(MainForm frm)
        {
            form1 = frm;
        }

        

        

        public static Users GetActiveUser
        {
            get { return activeUser; }
        }

        public static void SetActiveUser(Users User)
        {
            activeUser = User;
        }

        static bool CheckApplicationUpdate()
        {
            //string InstallFile = @"\\GV-PC\\Users\\GV\\Desktop\\TMS\\TMS_Setup.msi";
            string InstallFile = @"\\SERVERT\\TMS Update\\TMS_Setup.msi";
            string BatName = "c:\\windows\\temp\\update.bat";
            if (!File.Exists(InstallFile))
            {
                return false;
            }
            
            string InstallFileTmp = "C:\\Windows\\Temp\\TMS_Setup.msi";
            FileVersionInfo Curent = FileVersionInfo.GetVersionInfo(Application.ExecutablePath);
            string  New = GetMsiVersion(InstallFile).ToString();

            if ((Curent.FileVersion.ToString()) != (New + ".0"))
            {
                File.Copy(InstallFile, InstallFileTmp, true);
                string msg = "Достапна е нова верзија на " + Application.ProductName +
                             " .\r\n\r\nОткако ќе кликнете на ОК истата ке биде инсталирана.";
                MessageBox.Show(msg, "Updates available",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);

                string BatFile = "";
                string old_dir = Directory.GetCurrentDirectory();
                BatFile += "@echo off\r\n";
                BatFile += "ping localhost -n 2\r\n";
                
                BatFile += "C:\\WINDOWS\\system32\\msiexec.exe /i \"" +
                           InstallFileTmp + "\" /qr\r\n";
                BatFile += "cd \"" + old_dir + "\"\r\n";
                BatFile += "start \"\" " +
                           Environment.CommandLine + "\r\n";
                StreamWriter sw = new StreamWriter(BatName);
                sw.Write(BatFile);
                sw.Close();

                System.Diagnostics.ProcessStartInfo psi =
                  new System.Diagnostics.ProcessStartInfo();
                psi.FileName = BatName;
                psi.Arguments = "";
                psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = psi;
                p.Start();

                return true;
            }
            return false;
        }

        private static string GetMsiVersion(string installerPath)
        {
            Type t = Type.GetTypeFromProgID("WindowsInstaller.Installer");
            Installer inst = (Installer)Activator.CreateInstance(t);
            Database d = inst.OpenDatabase(installerPath,MsiOpenDatabaseMode.msiOpenDatabaseModeReadOnly);
            WindowsInstaller.View v = d.OpenView("SELECT * FROM Property WHERE Property = 'ProductVersion'");
            v.Execute(null);
            Record r = v.Fetch();
            string result = r.get_StringData(2);
            return result;
        }
    }
}
